<template>
  <div class="New_build">
    <div class="mask"></div>
    <div class="new_build">
      <div class="build-top">
        <p>{{ !$route.query.oid ? '新建资料（客户进货）' : '客户进货补单' }}</p>
        <i class="el-icon-close" @click="closeNewCS"></i>
      </div>

      <div class="build-info">
        <div class="build-info-1">
          <p>进货日期</p>
          <el-date-picker
            v-model="inputDate"
            type="date"
            value-format="yyyy-MM-dd HH:mm:ss"
            disabled
          > 
          </el-date-picker>
          <p>客户编号</p>
          <div class="infoBox">
            <!-- <el-input v-model="customerNo" @blur="customerNoBlur" :disabled="supplement"></el-input> -->
            <el-select
              v-model="customerName"
              filterable
              @change="
                (e) => {
                  this.customerNo = e
                  this.getCustomerDiscount()
                  this.getAllocationSequence()
                }
              "
              :disabled="supplement"
            >
              <el-option
                v-for="item in customerList"
                :key="item.value"
                :label="item.value + '  ' + item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          <p>单号</p>
          <el-input v-model="inputSequence" disabled></el-input>
          <p>客进序号</p>
          <el-input v-model="sequence" disabled></el-input>
        </div>
        <div class="build-info-2">
          <p>仓库</p>
          <div class="infoBox">
            <!-- <el-input v-model="warehouseNo" @blur="warehouseNoBlur" disabled></el-input> -->
            <el-select
              v-model="warehouseName"
              @change="
                (e) => {
                  this.warehouseNo = e
                }
              "
              disabled
              filterable
            >
              <el-option
                v-for="item in warehouseList"
                :key="item.value"
                :label="item.value + '  ' + item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          <p>折数</p>
          <el-input v-model="discount" :disabled="supplement"></el-input>
          <p style="margin-left: 10px">配货序号</p>
          <!-- <el-input v-model="cooperateSequence"></el-input> -->
          <el-select v-model="cooperateSequence" :disabled="supplement">
            <el-option
              v-for="item in cooperateSequenceList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <p>配货方式</p>
          <el-select v-model="cooperateWay" :disabled="supplement">
            <el-option
              v-for="item in cooperateWayList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
        <div class="build-info-3">
          <p>备注</p>
          <div class="sty">
            <el-input v-model="remark" :disabled="supplement"></el-input>
          </div>
        </div>

        <el-table
          id="codeTable"
          border
          :data="codeData"
          class="tb-edit"
          style="width: 100%; margin-bottom: 15px"
          max-height="148px"
          @cell-click="cellClick"
          :header-cell-style="{
            background: '#f4f4f4',
            padding: 0,
            height: '40px'
          }"
          :cell-style="{ padding: 0, height: '36px' }"
        >
          <el-table-column :label="header" width="150"> </el-table-column>
          <el-table-column prop="colorName" label="颜色" width="100">
          </el-table-column>

          <template v-for="i in sizeList">
            <el-table-column :prop="i" :label="i" :key="i + Math.random()">
              <template slot-scope="scope">
                <el-input
                  size="small"
                  class="innerInp"
                  v-model="scope.row[i]"
                  @blur="
                    handleInputBlurResult($event, {
                      index: scope.$index,
                      key: i,
                      result: scope.row[i]
                    })
                  "
                  @keyup.enter.native="inpEnter"
                >
                </el-input>
                <!-- <span>{{scope.row[i]}}</span> -->
              </template>
            </el-table-column>
          </template>
        </el-table>

        <div class="barcode">
          <p>条码扫描</p>
          <el-switch
            v-model="isBarcode"
            active-color="#409EFF"
            inactive-color="#C0C4CC"
            :disabled="creating"
          >
          </el-switch>
          <div style="display: flex; height: 20px">
            <p>条码选择</p>
            <div style="margin: 0">
              <el-radio
                :disabled="!isBarcode || creating"
                v-model="radio"
                label="1"
                >货号码</el-radio
              >
              <el-radio
                :disabled="!isBarcode || creating"
                v-model="radio"
                label="2"
                >ID码</el-radio
              >
              <!-- <el-radio v-model="radio1" label="1">出货金额下限有效</el-radio> -->
              <el-checkbox v-model="checked" :disabled="jxShippingAmount"
                >出货金额下限有效</el-checkbox
              >
            </div>
            <div style="margin: 0 0 0 50px">
              <i
                class="el-icon-question"
                style="color: #017aff; padding-right: 6px"
              ></i>
              <p>冲减单子. 点"货号"， 请按F7，把数量填成-1</p>
            </div>
          </div>
        </div>

        <div class="enterBarcode">
          <el-input
            ref="barcodeInput"
            @keyup.enter.native="barcodeEnter($event)"
            v-model="barcode"
            placeholder="扫描/输入货号或款号，输完按回车"
          >
          </el-input>
          <span>合计：{{ total }}</span>
        </div>

        <el-table
          height="210px"
          :data="barcodeData"
          style="width: 100%"
          :header-cell-style="{
            background: '#f4f4f4',
            padding: 0,
            height: '40px'
          }"
          :cell-style="{ padding: 0, height: '36px' }"
        >
          <el-table-column prop="kindsNumber" label="货号" width="160">
          </el-table-column>
          <el-table-column prop="colorName" label="颜色" width="80">
          </el-table-column>
          <el-table-column prop="sizeNo" label="尺码编号" width="80">
          </el-table-column>
          <el-table-column prop="sum" label="数量" width="60">
          </el-table-column>
          <el-table-column prop="onePrice" label="单价" width="100">
          </el-table-column>
          <el-table-column prop="money" label="金额" width="100">
          </el-table-column>
          <el-table-column prop="sellingPrice" label="售价" width="100">
          </el-table-column>
          <el-table-column prop="commodityName" label="品名" width="160">
          </el-table-column>
          <el-table-column prop="brandedName" label="品牌" width="160">
          </el-table-column>
          <el-table-column prop="entryTime" label="录入时间" width="160">
          </el-table-column>
        </el-table>
      </div>

      <div class="build-btn">
        <div style="margin: 5px 20px 0 0">
          <el-button @click="closeNewCS">关闭</el-button>
          <!-- <el-button type="primary" @click="save" plain>保存</el-button> -->
          <el-button type="primary" @click="continueInput">继续录入</el-button>
        </div>
      </div>
    </div>

    <div class="popup" :style="{ display: showPopup }">
      <div class="popup_t">
        <p>输入扫描数量</p>
        <i class="el-icon-close" @click="closePopup"></i>
      </div>
      <div class="popup_c">
        <p>请输入扫描数量</p>
        <p>如果不输入则扫描数量为1</p>
        <el-input
          v-model="scanNum"
          style="margin-top: 10px"
          @keyup.enter="closePopup"
        ></el-input>
        <!-- <input type="text" 
          class="popup_button" 
          v-model="scanNum"
          @keyup.enter="closePopup"> -->
      </div>
      <div class="popup_b">
        <el-button @click="closePopup">取消</el-button>
        <el-button type="primary" @click="closePopup">确定</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getOutMoneyLower,
  inputByKindsNumberContinue,
  inputByKindsNumber,
  getInfoByInputSequence,
  rfidInput,
  patchByAffirm
} from '../../../../network/customerInputTotal'
import { getKindsNumberList } from '../../../../network/artNo'
import { getClient } from '../../../../network/client'
import { getBarCode, searchKindsNumber } from '../../../../network/manufacturer'
import { getList } from '../../../../network/customerAllocationTotal'

import exportMethods from '../../../../components/mixins/exportMethods'
import cookieFn from '../../../../components/mixins/cookieFn'
import today from '../../../../components/mixins/today'

export default {
  mixins: [exportMethods, cookieFn, today],
  props: {
    sendData: {
      type: Object,
      default: {}
    },
    flag: {
      type: String,
      default: 'none'
    },
    pageSession: {
      type: String,
      default: ''
    },
    Str: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 条码规律详情
      manufacturerBarCode: {},
      kindsNumberMap: {},

      originalData: {},

      showPopup: 'none',
      inputDate: '',
      customerNo: '',
      customerName: '',
      customerList: [],
      inputSequence: '',
      sequence: '',
      warehouseNo: '',
      warehouseName: '',
      warehouseList: [],
      discount: 10,
      cooperateSequence: '',
      cooperateSequenceList: [],
      cooperateWay: '配货',
      cooperateWayList: [
        { value: '配货', label: '配货' },
        { value: '订货', label: '订货' },
        { value: '订断', label: '订断' },
        { value: '追断', label: '追断' }
      ],
      remark: '',

      header: '',
      sizeList: ['7', '9', '1', '3', '5', '7', 'F'],
      codeData: [],
      creating: false,
      isBarcode: false,
      radio: '1',
      checked: false,
      barcode: '',
      barcodeData: [],

      gatheringMoney: 0,
      outMoneyFloor: 0,
      outTotalMoney: 0,

      tmpData: {},
      tmpBarcodeData: [],

      scanNum: '1', //扫描数量 默认1
      supplement: false,

      // 出货金额有效
      jxShippingAmount: this.getCookie('jxShippingAmount') == '0',

      total: 0,

      isConfirm: false
    }
  },
  watch: {
    Str(a, b) {
      console.log(a)
    },
    sendData(a, b) {
      this.inputDate = a.inputDate || []
      this.isConfirm = Boolean(a.isConfirm)
      this.customerNo = a.customerNo
      this.customerName = a.customerName
      this.customerList = a.customerList
      this.inputSequence = a.inputSequence
      this.sequence = a.sequence
      this.warehouseNo = a.warehouseNo
      this.warehouseName = a.warehouseName
      this.warehouseList = a.warehouseList
      this.discount = a.discount
      this.cooperateSequence = a.cooperateSequence
      this.cooperateSequenceList = a.cooperateSequenceList
      this.cooperateWay = a.cooperateWay
      this.cooperateWayList = a.cooperateWayList
      this.remark = a.remark
    },
    checked(a, b) {
      if (a) {
        if (!this.customerNo) {
          this.$alert('客户编号不能为空', '', {
            confirmButtonText: '确定'
          })
          return
        }
        getOutMoneyLower({ customerNo: this.customerNo }).then((res) => {
          if (res.data.code == 200) {
            // 每当新录入一条，历史出货金就加那条的金额（数量*单价），
            // 如果历史出货金-历史付款金>出货金额下限，做一个提示，但不影响继续录入

            // 历史付款金
            this.gatheringMoney = res.data.data.gatheringMoney
            // 出货金额下限
            this.outMoneyFloor = res.data.data.outMoneyFloor
            // 历史出货金
            this.outTotalMoney = res.data.data.outTotalMoney

            if (this.barcodeData.length) {
              this.total = 0
              this.barcodeData.forEach((e) => {
                this.outTotalMoney += e.money
                this.total += Number(e.sum)
              })
            }
          }
        })
      }
    },
    flag(a, b) {
      if (this.creating) this.creating = false
      if (a == 'block') {
        this.total = 0
        if (this.$route.query.oid) {
          this.supplement = true
          getInfoByInputSequence({ inputSequence: this.$route.query.oid }).then(
            (res) => {
              this.barcodeData = res.data.data
              this.total = 0
              this.kindsNumberMap = {}
              res.data.data.forEach((e) => {
                this.kindsNumberMap[e.kindsNumber] = e.sum
                this.total += Number(e.sum)
              })
            }
          )
        } else {
          this.supplement = false
          this.sequence = ''
        }
      }
    },
    barcode(a, b) {
      this.barcode = a.toUpperCase().trim()
    },
    customerNo(a, b) {
      this.customerNo = a.toUpperCase().trim()
    },
    inputSequence(a, b) {
      this.inputSequence = a.toUpperCase().trim()
    }
  },
  methods: {
    getCustomerDiscount() {
      getClient({ no: this.customerNo }).then((res) => {
        console.log(res)
        if (res.data.data != null) {
          this.discount = res.data.data[0].sellDiscount
        }
      })
    },
    sibling(e) {
      let s = []
      let pp = e.parentNode.parentNode.children
      for (let j = 0; j < pp.length; j++) {
        let p = pp[j].children
        for (let i = 0, pl = p.length; i < pl; i++) {
          if (p[i] !== e) s.push(p[i])
        }
      }
      return s
    },
    handleInputBlurResult(e, { index, key, result }) {
      e.target.parentNode.parentNode.parentNode.classList.remove('activeCell')
      let r = /^(0|[1-9][0-9]*|-[1-9][0-9]*)$/
      if (result != 0) {
        result = result.replace(/\b(0+)/gi, '')
      }
      if (!r.test(result) && result) {
        this.$alert('数量请输入整数', '', {
          confirmButtonText: '确定'
        })
        this.codeData[index][key] = 0
        return
      }
      this.codeData[index][key] = result
    },
    cellClick(row, column, cell, event) {
      // console.log(row)  //当行的全部数据
      // console.log(column)  //当列的全部数据
      // console.log(cell)  //点击格的html代码  td>div
      // console.log(event)  //MouseEvent
      // console.log(cell.innerHTML)

      // console.log(cell.children[0].children[0].children)
      // cell.children[0].children[0].children[0].focus()
      cell.classList.add('activeCell')
      let s = this.sibling(cell)
      // console.log(s)
      s.forEach((e) => {
        e.classList.remove('activeCell')
      })
    },
    inpEnter(e) {
      e.target.parentNode.parentNode.parentNode.classList.remove('activeCell')
    },

    // 出货金额下限
    checkTotalMoney() {
      if (this.outMoneyFloor < this.outTotalMoney - this.gatheringMoney) {
        this.$message({
          message: '超出出货金额下限',
          type: 'warning',
          offset: 300
        })
      }
    },

    // 扫描
    barcodeEnter() {
      if (this.barcode) {
        if (!this.isBarcode) {
          // 手输款号
          getKindsNumberList({ kindsNumberStr: this.barcode }).then((res) => {
            console.log(res)
            if (res.data.data.data.length) {
              this.header = res.data.data.data[0].styleNumber
              this.$emit('inpNumChange')
              // 品牌公司查条码规律详情
              console.log(res.data.data.data[0].brandedCompany)
              getBarCode({
                company: res.data.data.data[0].brandedCompany
              }).then((res) => {
                console.log(res)
                this.manufacturerBarCode = res.data.data[0]
              })
              // console.log(this.manufacturerBarCode)
              // 输入款号显示中间表和尺码信息   ZZZ-AAS
              res.data.data.data.sort((a, b) => {
                return a.relevanceSize.localeCompare(b.relevanceSize)
              })
              let tmp = res.data.data.data
              this.tmpBarcodeData = tmp
              // console.log(tmp)

              // 中间表  尺码表头
              this.sizeList = [tmp[0].size]
              let isExistSize = 0
              for (const i of tmp) {
                for (const j of this.sizeList) {
                  if (j == i.size) {
                    isExistSize = 0
                    break
                  }
                  isExistSize = 1
                }
                if (isExistSize) {
                  this.sizeList.push(i.size)
                }
              }

              // 中间表
              let tmpCodeData = [
                { colorNo: tmp[0].colorNo, colorName: tmp[0].colorName }
              ]
              let isExistColor = 0
              for (const i of tmp) {
                for (const j of tmpCodeData) {
                  if (j.colorName == i.colorName) {
                    isExistColor = 0
                    break
                  }
                  isExistColor = 1
                }
                if (isExistColor) {
                  tmpCodeData.push({
                    colorNo: i.colorNo,
                    colorName: i.colorName
                  })
                }
              }
              tmpCodeData.forEach((e) => {
                this.sizeList.forEach((f) => {
                  e[f] = ''
                })
              })
              this.codeData = tmpCodeData
              let codeTable = document.getElementById('codeTable')
              let inputs = codeTable.getElementsByTagName('input')
              // console.log(inputs)
              let int = setInterval(() => {
                clearInterval(int)
                inputs[0].focus()
                inputs[inputs.length - 1].onkeyup = (e) => {
                  if (window.event.keyCode == 13) {
                    this.continueInput()
                    inputs[inputs.length - 1].onkeyup = () => {}
                  }
                }
              }, 100)
            } else {
              this.$message('此货号/款号无数据')
              this.$refs.barcodeInput.focus()
            }
          })
        } else {
          this.continueInput()
        }
      }
    },

    closeNewCS() {
      // if (!this.$route.query.oid && this.barcodeData.length) {
      //   this.$alert('数据未保存', '', {
      //     confirmButtonText: '确定'
      //   })
      //   return
      // }
      this.Str = ''
      this.$route.query.oid = ''
      this.save()
      this.codeData = []
      this.barcodeData = []
      this.originalData = {}
      this.isBarcode = false
      this.barcode = ''
      this.inputDate = this.getNowTime1()
      this.$emit('closeNewCS')
    },

    // 继续录入
    continueInput() {
      console.log(this.Str)
      if (!this.inputDate) {
        this.$alert('日期不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (!this.customerNo) {
        this.$alert('客户不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (!this.warehouseNo) {
        this.$alert('仓库不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (!this.discount) {
        this.$alert('折数不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }

      // 是否有信息变动
      let isNew = false

      if (JSON.stringify(this.originalData) == '{}') {
        // 第一次点读卡，记录原始数据
        this.originalData.inputDate = this.inputDate
        this.originalData.customerNo = this.customerNo
        this.originalData.inputSequence = this.inputSequence
        this.originalData.warehouseNo = this.warehouseNo
        this.originalData.discount = this.discount
        this.originalData.cooperateWay = this.cooperateWay
        this.originalData.cooperateSequence = this.cooperateSequence
        this.originalData.remark = this.remark
      } else {
        // 判断是否修改了数据
        for (const key in this.originalData) {
          if (this.originalData.hasOwnProperty(key)) {
            const e = this.originalData[key]
            if (e != this[key]) {
              // 修改了数据 重新赋值
              isNew = true
              this.originalData.inputDate = this.inputDate
              this.originalData.manufacturerNo = this.manufacturerNo
              this.originalData.inputSequence = this.inputSequence
              this.originalData.warehouseNo = this.warehouseNo
              this.originalData.discount = this.discount
              this.originalData.cooperateWay = this.cooperateWay
              this.originalData.cooperateSequence = this.cooperateSequence
              this.originalData.remark = this.remark
              break
            }
          }
        }
      }

      let validList = []
      if (this.sequence != '' && !isNew) {
        // 有序号并且信息没改，再点读卡，传右表
        // console.log('没有数据变动')
        validList = this.barcodeData
      } else {
        // console.log('第一次或有数据变动')
        // 有数据变动，进厂序号改空
        this.sequence = ''
        this.total = 0
        this.barcodeData = []
      }

      if (this.isBarcode && this.radio == 2) {
        let d = {
          customerDTO: {
            pageSession: this.pageSession,
            inputDate: this.inputDate,
            customerNo: this.customerNo,
            sequence: this.sequence,
            inputSequence: this.inputSequence,
            warehouseNo: this.warehouseNo,
            discount: this.discount,
            cooperateWay: this.cooperateWay,
            remark: this.remark,
            flagToken: this.Str
          },
          rfidShowCodeList: [this.barcode],
          validList
        }
        console.log(d)
        rfidInput(JSON.stringify(d)).then((res) => {
          console.log(res)
          if (res.data.code == 200) {
            this.barcode = ''
            this.$refs.barcodeInput.focus()
            let tmpList = res.data.data.validList

            if (tmpList) {
              this.sequence = tmpList[0].sequence || ''
            }
            if (this.sequence) {
              getInfoByInputSequence({ inputSequence: this.sequence }).then(
                (res) => {
                  this.barcodeData = res.data.data
                  this.kindsNumberMap = {}
                  this.total = 0
                  res.data.data.forEach((e) => {
                    this.kindsNumberMap[e.kindsNumber] = e.sum
                    this.total += Number(e.sum)
                  })
                }
              )
            }

            if (res.data.data.outOfStock && res.data.data.outOfStock.length) {
              // 库存不足导出
              this.exportRaw(String(res.data.data.outOfStock), '库存不足.txt')
            }
            if (
              res.data.data.errorRfidList &&
              res.data.data.errorRfidList.length
            ) {
              // 导出errorRfid
              this.exportRaw(
                String(res.data.data.errorRfidList),
                '库存不足Rfid.txt'
              )
            }
            if (
              res.data.data.outOfStockPlus &&
              res.data.data.outOfStockPlus.length
            ) {
              // 部分成功导出
              this.exportRaw(
                String(res.data.data.outOfStockPlus),
                '部分成功.txt'
              )
            }
          } else {
            if (this.sequence) {
              getInfoByInputSequence({ inputSequence: this.sequence }).then(
                (res) => {
                  this.barcodeData = res.data.data
                  this.kindsNumberMap = {}
                  this.total = 0
                  res.data.data.forEach((e) => {
                    this.kindsNumberMap[e.kindsNumber] = e.sum
                    this.total += Number(e.sum)
                  })
                }
              )
            }
          }
        })
        // rfidInput
        return
      }

      let kindsNumberNumMap = {}
      if (this.isBarcode) {
        // 扫描
        if (this.radio == 1) {
          // 扫描货号码
          kindsNumberNumMap[this.barcode] = this.scanNum
        } else if (this.radio == 2) {
          // 扫描ID码
          searchKindsNumber({
            // 条码与货号是否一致
            isSame: false,
            // 是否开启条码扫描
            isScanner: true,
            searchValue: this.barcode
          }).then((res) => {
            console.log(res)
            kindsNumberNumMap[res.data.data[0].kindsNumber] = this.scanNum
          })
        }
      } else {
        // 输入
        let knList = []
        this.codeData.forEach((e) => {
          let c = e.colorNo
          this.sizeList.forEach((f) => {
            if (this.manufacturerBarCode.styleColorSize) {
              // 型尺色

              if (this.manufacturerBarCode.styleColor) {
                // 款号与尺码之间有 -

                if (this.manufacturerBarCode.colorSize) {
                  // 色号与尺码之间有 -
                  knList.push({
                    kindsNumber: `${this.header}-${f}-${c}`,
                    sum: e[f]
                  })
                } else {
                  // 色号与尺码之间没有 -
                  knList.push({
                    kindsNumber: `${this.header}-${f}${c}`,
                    sum: e[f]
                  })
                }
              } else {
                // 款号与尺码之间没有 -

                if (this.manufacturerBarCode.colorSize) {
                  // 色号与尺码之间有 -
                  knList.push({
                    kindsNumber: `${this.header}${f}-${c}`,
                    sum: e[f]
                  })
                } else {
                  // 色号与尺码之间没有 -
                  knList.push({
                    kindsNumber: `${this.header}${f}${c}`,
                    sum: e[f]
                  })
                }
              }
            } else {
              // 型色尺

              if (this.manufacturerBarCode.styleColor) {
                // 款号与颜色之间有 -

                if (this.manufacturerBarCode.colorSize) {
                  // 色号与尺码之间有 -
                  knList.push({
                    kindsNumber: `${this.header}-${c}-${f}`,
                    sum: e[f]
                  })
                } else {
                  // 色号与尺码之间没有 -
                  knList.push({
                    kindsNumber: `${this.header}-${c}${f}`,
                    sum: e[f]
                  })
                }
              } else {
                // 款号与颜色之间没有 -

                if (this.manufacturerBarCode.colorSize) {
                  // 色号与尺码之间有 -
                  knList.push({
                    kindsNumber: `${this.header}${c}-${f}`,
                    sum: e[f]
                  })
                } else {
                  // 色号与尺码之间没有 -
                  knList.push({
                    kindsNumber: `${this.header}${c}${f}`,
                    sum: e[f]
                  })
                }
              }
            }
          })
        })
        // console.log(knList)
        for (const i of knList) {
          if (i.sum == '' || i.sum == 0) continue
          kindsNumberNumMap[i.kindsNumber] = i.sum
        }
      }
      if (JSON.stringify(kindsNumberNumMap) == '{}') {
        this.$alert('无数据无法继续录入', '', {
          confirmButtonText: '确定'
        })
        return
      }
      let d = {
        // 是否是补单（补货数据（0否 1是））
        isReplenishment: this.sequence ? 1 : 0,
        inputDate: this.$route.query.oid
          ? this.inputDate.slice(0, 10)
          : this.inputDate,
        customerNo: this.customerNo,
        inputSequence: this.inputSequence,
        sequence: this.sequence,
        warehouseNo: this.warehouseNo,
        discount: this.discount,
        cooperateWay: this.cooperateWay,
        remark: this.remark,
        kindsNumberNumMap,
        flagToken: this.Str
      }
      console.log(d)
      this.checkTotalMoney()
      // return
      if (this.isConfirm) {
        patchByAffirm(JSON.stringify(d)).then((res) => {
          console.log(res)
          if (res.data.code == 200) {
            if (!this.creating) this.creating = true
            this.barcode = ''
            this.header = ''
            this.codeData = []
            this.$refs.barcodeInput.focus()

            if (res.data.data.validList && res.data.data.validList.length) {
              this.sequence = res.data.data.validList[0].sequence
              let isExist = 0
              res.data.data.validList.forEach((e) => {
                this.total += Number(e.sum)
                for (const i of this.barcodeData) {
                  if (e.kindsNumber == i.kindsNumber) {
                    i.sum += Number(e.sum)
                    i.money = (i.sum * i.sellingPrice * i.discount) / 10
                    isExist = 1
                    break
                  }
                  isExist = 0
                }
                if (!isExist) {
                  this.barcodeData.unshift(e)
                }
              })
            }
            if (res.data.data.outOfStock && res.data.data.outOfStock.length) {
              // 库存不足导出
              this.exportRaw(String(res.data.data.outOfStock), '库存不足.txt')
            }
            if (
              res.data.data.outOfStockPlus &&
              res.data.data.outOfStockPlus.length
            ) {
              // 部分成功导出
              this.exportRaw(
                String(res.data.data.outOfStockPlus),
                '部分成功.txt'
              )
            }
            this.removeInvalid()
            // this.save()
          }
        })
      } else {
        console.log(d)
        inputByKindsNumberContinue(JSON.stringify(d)).then((res) => {
          if (res.data.code == 200) {
            if (!this.creating) this.creating = true
            this.barcode = ''
            this.header = ''
            this.codeData = []
            this.$refs.barcodeInput.focus()

            if (res.data.data.validList && res.data.data.validList.length) {
              this.sequence = res.data.data.validList[0].sequence
              let isExist = 0
              res.data.data.validList.forEach((e) => {
                this.total += Number(e.sum)
                for (const i of this.barcodeData) {
                  if (e.kindsNumber == i.kindsNumber) {
                    i.sum += Number(e.sum)
                    i.money = (i.sum * i.sellingPrice * i.discount) / 10
                    isExist = 1
                    break
                  }
                  isExist = 0
                }
                if (!isExist) {
                  this.barcodeData.unshift(e)
                }
              })
            }
            if (res.data.data.outOfStock && res.data.data.outOfStock.length) {
              // 库存不足导出
              this.exportRaw(String(res.data.data.outOfStock), '库存不足.txt')
            }
            if (
              res.data.data.outOfStockPlus &&
              res.data.data.outOfStockPlus.length
            ) {
              // 部分成功导出
              this.exportRaw(
                String(res.data.data.outOfStockPlus),
                '部分成功.txt'
              )
            }
            this.removeInvalid()
            // this.save()
          }
        })
      }
    },
    removeInvalid() {
      let length = this.barcodeData.length
      for (let i = 0; i < length; i++) {
        const e = this.barcodeData[i]
        if (!Number(e.sum)) {
          this.barcodeData.splice(i, 1)
          i--
        }
      }
    },

    // 保存
    save() {
      if (this.barcodeData != '') {
        this.$message({
          message: '保存成功',
          type: 'success'
        })
      }
      let send = {
        inputDate: this.inputDate,
        customerNo: this.customerNo,
        customerName: this.customerName,
        inputSequence: this.inputSequence,
        sequence: this.sequence,
        warehouseNo: this.warehouseNo,
        warehouseName: this.warehouseName,
        discount: this.discount,
        cooperateWay: this.cooperateWay,
        remark: this.remark,
        supList: this.barcodeData
      }
      // 发送到父组件数据
      this.$emit('saveNew', send)
      this.header = ''
      this.barcodeData = []
      this.originalData = {}
      // this.closeNewCS()
      return
      if (!this.inputDate) {
        this.$alert('日期不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (!this.customerNo) {
        this.$alert('客户不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (!this.warehouseNo) {
        this.$alert('仓库不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (!this.discount) {
        this.$alert('折数不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }

      // 货号：数量 map集合
      let kindsNumberNumMap = {}
      // 补单新货号对象集合
      let replenishmentNewKindsNumberMap = {}

      this.barcodeData.forEach((e) => {
        replenishmentNewKindsNumberMap[e.kindsNumber] = e
        kindsNumberNumMap[e.kindsNumber] = e.sum
      })

      if (this.sequence) {
        // 补单
        for (const i in this.kindsNumberMap) {
          for (const k in kindsNumberNumMap) {
            if (kindsNumberNumMap.hasOwnProperty(k)) {
              if (i == k) {
                // delete kindsNumberNumMap[k]
                delete replenishmentNewKindsNumberMap[k]
                break
              }
            }
          }
        }
      }

      let validList = []
      this.barcodeData.forEach((e) => {
        for (const key in this.kindsNumberMap) {
          if (key == e.kindsNumber) {
            validList.push(e)
            break
          }
        }
      })

      let d = {
        customerDTO: {
          // 是否是补单（补货数据（0否 1是））
          isReplenishment: this.$route.query.oid ? 1 : 0,
          inputDate: this.$route.query.oid
            ? this.inputDate.slice(0, 10)
            : this.inputDate,
          customerNo: this.customerNo,
          inputSequence: this.inputSequence,
          sequence: this.sequence,
          warehouseNo: this.warehouseNo,
          discount: this.discount,
          cooperateWay: this.cooperateWay,
          cooperateSequence: this.cooperateSequence,
          remark: this.remark,
          kindsNumberNumMap,
          replenishmentNewKindsNumberMap
        },
        validList: this.$route.query.oid ? validList : this.barcodeData
      }
      console.log(d)
      inputByKindsNumber(JSON.stringify(d)).then((res) => {
        console.log(res)
        if (res.data.code == 200) {
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          let send = {
            inputDate: this.inputDate,
            customerNo: this.customerNo,
            customerName: this.customerName,
            inputSequence: this.inputSequence,
            sequence: this.sequence,
            warehouseNo: this.warehouseNo,
            warehouseName: this.warehouseName,
            discount: this.discount,
            cooperateWay: this.cooperateWay,
            remark: this.remark,
            supList: this.barcodeData
          }
          // 发送到父组件数据
          this.$emit('saveNew', send)
          this.header = ''
          this.barcodeData = []
          this.closeNewCS()
        } else {
          this.$message.error('保存失败')
        }
      })
    },

    // 客户编号失去焦点
    customerNoBlur() {
      if (this.customerNo != '') {
        for (const i of this.customerList) {
          if (this.customerNo == i.value) {
            this.customerName = i.label
            this.getAllocationSequence()
            return
          }
        }
        this.$alert('无此客户编号', '', {
          confirmButtonText: '确定'
        })
        this.customerNo = ''
        this.customerName = ''
      } else {
        this.customerName = ''
      }
    },
    // 仓库编号失去焦点
    warehouseNoBlur() {
      if (this.warehouseNo != '') {
        for (const i of this.warehouseList) {
          if (this.warehouseNo == i.value) {
            this.warehouseName = i.label
            return
          }
        }
        this.$alert('无此仓库编号', '', {
          confirmButtonText: '确定'
        })
        this.warehouseNo = ''
        this.warehouseName = ''
      } else {
        this.warehouseName = ''
      }
    },
    getAllocationSequence() {
      this.cooperateSequenceList = []
      getList({ customerNo: this.customerNo }).then((res) => {
        if (res.data.data.leftTwo && res.data.data.leftTwo.length) {
          res.data.data.leftTwo.forEach((e) => {
            this.cooperateSequenceList.push({
              value: e.allocationCargoSequence,
              label: e.allocationCargoSequence
            })
          })
        }
      })
    },

    // 关闭扫描数量
    closePopup() {
      this.showPopup = 'none'
    }
  },
  mounted() {
    let _this = this
    document.onkeydown = function (event) {
      let e = event || window.event || arguments.callee.caller.arguments[0]
      if (e && e.keyCode == 118) {
        // 按 F7
        if (_this.showPopup == 'none') {
          _this.showPopup = 'block'
        } else {
          _this.showPopup = 'none'
        }
      }
    }
  }
}
</script>

<style scoped>
.build-info-3 {
  display: flex;
  margin-bottom: 15px;
}
.build-info-3 p {
  display: inline-block;
  width: 80px;
  text-align: right;
  margin: 2px 15px 0 0;
}
.middle {
  padding: 10px 15px;
}
.middle p {
  padding-bottom: 10px;
}
._top {
  display: flex;
  width: 100%;
  height: 40px;
  padding: 10px 15px;
  justify-content: space-between;
  background: #f8f8f8;
  font-weight: 700;
}
.scanning {
  width: 400px;
  height: 200px;
  background: white;
  box-shadow: 0 3px 3px 3px #e7e4e4;
  position: abbuildlute;
  top: 30%;
  left: 30%;
  z-index: 1000;
}
/* 新建资料 */
.mask {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  opacity: 0.3;
  z-index: 9;
}
.new_build {
  position: fixed;
  top: 7%;
  left: 50%;
  transform: translateX(-50%);
  width: 1070px;
  z-index: 99;
  background-color: white;
  overflow: auto;
}
.new_build .build-top {
  height: 40px;
  background-color: #f8f8f8;
}
.new_build .build-top p {
  float: left;
  line-height: 40px;
  padding-left: 20px;
  font-weight: 700;
}
.new_build .build-top i {
  float: right;
  line-height: 40px;
  padding: 0 16px;
}

.new_build input {
  height: 30px;
  border: buildlid 1px #dcdfe6;
  border-radius: 5px;
  margin-left: 10px;
}
.new_build input:focus {
  outline: none;
  border: buildlid 1px #409eff;
}
.new_build .build-info-2 .inp-2 {
  margin-right: 15px;
}
.build-info {
  padding: 0 15px;
  padding-bottom: 10px;
  /* border-bottom: buildlid #f2f2f2 2px; */
}
.build-info-1 p,
.build-info-2 p {
  display: inline-block;
  width: 80px;
  text-align: right;
  margin-right: 15px;
}
.build-info-1 p:nth-child(3) {
  margin-left: 10px;
}
.new_build .build-info-1 .inp-2 {
  margin-right: 43px;
}
.build-info .build-info-2 {
  margin-bottom: 10px;
}
.build-info .barcode p {
  display: inline;
  margin-right: 15px;
}
.build-info .barcode div {
  margin-top: 15px;
}
.barcode {
  margin-top: 15px;
}

.barcode-info-1 p,
.barcode-info-2 p {
  display: inline-block;
  width: 96px;
  text-align: right;
  margin-right: 9px;
}
.barcode-info-1 p:first-child,
.barcode-info-2 p:first-child {
  width: 65px;
}
.colorBox,
.infoBox {
  display: inline;
}

.enterBarcode {
  height: 60px;
  background-color: #f2f2f2;
  margin: 15px 0;
}

.build-btn {
  text-align: right;
  margin-bottom: 10px;
}

.popup {
  width: 400px;
  height: 200px;
  border: 1px solid #dbdbdb;
  box-shadow: 0 2px 2px 2px #dbdbdb;
  z-index: 999;
  position: absolute;
  left: 50%;
  top: 50%;
  margin: -100px 0 0 -200px;
  background: white;
  /* display: block; */
}
.popup_t {
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 40px;
  background: rgb(244, 244, 244);
  padding: 8px 15px;
}
.popup_t p {
  font-weight: 700;
}
.popup_c {
  padding: 8px 15px;
}
.popup_button {
  margin: 5px 0 0 0;
  width: 94%;
  height: 30px;
  padding: 0 10px;
  border: 1px solid#dbdbdb;
  border-radius: 3px;
}
.popup_b {
  margin: 10px 0 0 0;
  padding-left: 230px;
}
</style>

<style>
.New_build .build-info-1 .el-input,
.New_build .build-info-3 .el-input {
  width: 425px;
}
.New_build .build-info-1 .el-input,
.New_build .build-info-2 .el-input {
  /* margin: 10px 20px 0 10px; */
  margin-top: 10px;
  width: 160px;
}
.New_build .el-input__inner {
  height: 30px !important;
}
.New_build .el-input__icon {
  line-height: 30px !important;
}
.build-info .barcode .el-switch {
  margin: 0 !important;
}

.New_build .enterBarcode .el-input {
  width: 535px;
  margin: 14px 17px;
}

.colorBox .el-input {
  width: 73px;
  margin-right: 10px;
}
.New_build .build-info-1 .infoBox .el-input,
.New_build .build-info-2 .infoBox .el-input {
  margin: 0 10px 0 0;
  width: 60px;
}
.New_build .build-info-1 .infoBox .el-input--suffix,
.New_build .build-info-2 .infoBox .el-input--suffix {
  width: 160px;
}
.New_build .colorBox .el-input--suffix {
  width: 108px;
}
.New_build .build-info-4 .el-form-item {
  margin-bottom: 0;
}
.New_build .build-info-4 .el-table .cell {
  box-sizing: border-box;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
  word-break: break-all;
  line-height: 41px;
  padding-right: 10px;
  height: 40px;
}
.New_build .build-info-4 .el-input__inner {
  border: 0px;
}
.New_build .build-info-4 .el-input__inner:focus {
  border: 1px solid #017aff;
}
</style>
